package org.lex.game.sudoku.view.solver;

import javax.swing.JProgressBar;

import org.lex.game.sudoku.model.SudokuModel;
import org.lex.game.sudoku.model.solver.Decision;
import org.lex.game.sudoku.model.solver.SolverObserver;

public class ProgressBarSolverObserver extends JProgressBar implements SolverObserver {
	private static final long serialVersionUID = -6247570654410423933L;
	private SudokuModel model = null;

	public ProgressBarSolverObserver() {
		super(JProgressBar.HORIZONTAL, 0, 10);
		initialize();
	}

	public void setSudokuModel(SudokuModel model) {
		this.model = model;
		this.setMaximum(model.getOriginalEmptyCellsCount());
		this.updateProgress();
	}

	private void initialize() {
		this.setIndeterminate(false);
		this.setStringPainted(true);
		this.setValue(this.getMaximum());
	}

	@Override
	public void beginDecision(Decision d) {
		this.updateProgress();
	}

	@Override
	public void fillCell(int row, int col, int num) {
		this.updateProgress();
	}

	@Override
	public void rollbackDecision(Decision d, int cellCount) {
		this.updateProgress();
	}

	@Override
	public void reset() {
		this.updateProgress();
	}

	private void updateProgress() {
		int totalCount = this.getMaximum();
		int emptyCount = this.model.getCurrentEmptyCellsCount();
		int filledCount = totalCount - emptyCount;
		this.setValue(filledCount);
		this.setString(filledCount + "/" + totalCount + " empty cells filled");
	}
}
